<?php
namespace app\admin\controller;

use app\admin\controller\Base;
use app\common\model\UserCard;
use app\common\model\UserMain;
use app\common\model\UserMeal;
use app\common\model\UserMealOrder;
use app\common\model\UserRecharge;
use app\common\model\WebSite;
use think\facade\Request;
use think\facade\Validate;
use think\facade\View;

class Announce extends Base
{
    public function index()
    {
        $meal_list = UserMeal::order('meal_id', 'desc')->paginate(30);
        return View::assign([
            'meal_list' => $meal_list,
            'page'      => $meal_list->render(),
        ])->fetch();
    }

    public function add_meal()
    {
        if (Request::isAjax() && Request::isPost()) {
            $post     = Request::post();
            $validate = Validate::rule([
                'title' => 'require',
                'type'  => 'require',
                'price' => 'require',
            ])->message([
                'title.require' => '套餐名称必填',
                'type.require'  => '套餐类型必填',
                'price.require' => '套餐价格必填',
            ]);

            if (!$validate->check($post)) {
                return show_error($validate->getError());
            }
            UserMeal::create($post);
            return show_success('套餐添加成功', 'admin/announce/index');
        }
        $web_site_list = WebSite::order('site_id', 'desc')->select();
        return View::assign([
            'web_site_list' => $web_site_list,
        ])->fetch('edit_meal');
    }

    public function card()
    {
        $map = $page_query = [];
        if ($start_create_time = Request::param('start_create_time', '')) {
            $map[]                           = ['create_time', '>=', $start_create_time];
            $page_query['start_create_time'] = $start_create_time;
        }
        if ($start_end_time = Request::param('start_end_time', '')) {
            $map[]                        = ['create_time', '<=', $start_end_time];
            $page_query['start_end_time'] = $start_end_time;
        }
        if ($start_out_time = Request::param('start_out_time', '')) {
            $map[]                        = ['out_time', '>=', $start_out_time];
            $page_query['start_out_time'] = $start_out_time;
        }
        if ($end_out_time = Request::param('end_out_time', '')) {
            $map[]                      = ['out_time', '<=', $end_out_time];
            $page_query['end_out_time'] = $end_out_time;
        }
        if ($card_id = Request::param('card_id', '')) {
            $map[]                 = ['card_id', 'like', '%' . $card_id . '%'];
            $page_query['card_id'] = $card_id;
        }
        if ($type = Request::param('type', '')) {
            $map[]              = ['type', '=', $type];
            $page_query['type'] = $type;
        }
        $status = Request::param('status', '');
        if ($status !== '') {
            $map[]                = ['status', '=', $status];
            $page_query['status'] = $status;
        }
        $card_list = UserCard::where($map)->order('create_time', 'desc')->paginate([
            'list_rows' => 20,
            'query'     => $page_query,
        ]);

        foreach ($card_list as $key => $val){
                $uid = $val['use_uid'];

                if (!empty($uid)){
                    $user =  UserMain::where(['uid' => $uid])->find();
                    $card_list[$key]['use_username'] = $user['username'];
                }
        }

        return View::assign([
            'card_list' => $card_list,
            'page'      => $card_list->render(),
        ])->fetch();
    }

    public function card_add()
    {
        global $_G;
      
        if (Request::isAjax() && Request::isPost()) {
            $post     = Request::post();
            $card_ids = [];
            for ($i = 0; $i < (int) $post['numbers']; $i++) {
                $card_ids[$i] = replace_random_str($post['card_id']);
            }
            foreach (UserCard::where('card_id', 'in', $card_ids)->field('card_id')->select() as $old) {
                $k = array_search($old['card_id'], $card_ids);
                unset($card_ids[$k]);
            }
            $new_count = 0;
			
			if ($post['type'] == 0){
				$times = 10;
			}else{
				$times = -1;
			}
			
            foreach ($card_ids as $k => $card_id) {
                UserCard::create([
                    'uid'            => $_G['uid'],
                    'card_id'        => $card_id,
                    'type'           => $post['type'],
                    'times' => $times,
                    'status'         => 1,
                ]);

                $new_count++;
            }
            return show_success('本次成功生成' . $new_count . '张充值卡！', 'admin/announce/card');
        }
        return View::fetch();
    }

    public function card_delete($card_id = '')
    {
        if (!Request::isAjax()) {
            return show_error('请求类型错误');
        }
        $card = UserCard::where('card_id', '=', $card_id)->find();
        if (empty($card)) {
            return show_error('指定数据不存在');
        }
        $card->delete();
        return show_success('数据删除成功', 'admin/announce/card');
    }

    public function card_search()
    {
        if (Request::isPost()) {
            $param = [];
            if ('' !== $start_create_time = Request::post('start_create_time', '')) {
                $param['start_create_time'] = $start_create_time;
            }
            if ('' !== $end_create_time = Request::post('end_create_time', '')) {
                $param['end_create_time'] = $end_create_time;
            }
            if ('' !== $start_out_time = Request::post('start_out_time', '')) {
                $param['start_out_time'] = $start_out_time;
            }
            if ('' !== $end_out_time = Request::post('end_out_time', '')) {
                $param['end_out_time'] = $end_out_time;
            }
            if ('' !== $card_id = Request::post('card_id', '')) {
                $param['card_id'] = $card_id;
            }
            if ('' !== $type = Request::post('type', '')) {
                $param['type'] = $type;
            }
            if ('' !== $status = Request::post('status', '')) {
                $param['status'] = $status;
            }
            return redirect('admin/announce/card', $param);
        }
        return View::fetch();
    }

    public function card_export()
    {
        if (Request::isPost()) {
            $map =  [];
            if ($start_create_time = Request::post('start_create_time', '')) {
                $map[] = ['create_time', '>=', strtotime($start_create_time)];
            }
            if ($end_create_time = Request::post('end_create_time', '')) {
                $map[] = ['create_time', '<=', strtotime($end_create_time)];
            }
            if ($card_id = Request::post('card_id', '')) {
                $map[] = ['card_id', 'like', '%' . $card_id . '%'];
            }
            if ($type = Request::post('type', '')) {
                $map[] = ['type', '=', $type];
            }
            $status = Request::post('status', '');

            if (!empty($status)){
                $map[] = ['status', '=', intval($status)];
            }

            $expCellName = [];
            foreach (Request::post('fields/a', []) as $field => $name) {
                $expCellName[] = [$field, $name];
            }
            $card_list   = UserCard::where($map)->select();

            $cellNum     = count($expCellName);
            $dataNum     = count($card_list);
            $objPHPExcel = new \PHPExcel();
            $cellName    = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ'];
            for ($i = 0; $i < count($expCellName); $i++) {
                $objPHPExcel->getActiveSheet()->getColumnDimension($cellName[$i])->setWidth(15);
            }
            $objPHPExcel->getActiveSheet(0)->mergeCells('A1:' . $cellName[$cellNum - 1] . '1');
            $objPHPExcel->getActiveSheet()->setCellValue('A1', '充值卡密')->getStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            for ($i = 0; $i < $cellNum; $i++) {
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i] . '2', $expCellName[$i][1]);
            }
            for ($i = 0; $i < $dataNum; $i++) {
                for ($j = 0; $j < $cellNum; $j++) {
                    if (in_array($expCellName[$j][0], ['status', 'type'])) {
                        $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j] . ($i + 3), $card_list[$i][$expCellName[$j][0] . '_text']);
                    } else {
                        $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j] . ($i + 3), $card_list[$i][$expCellName[$j][0]]);
                    }
                }
            }
            $filename = '充值卡密';
            ob_end_clean();
            header('pragma:public');
            header('Content-type:application/octet-stream;charset=utf-8;name="' . $filename . '.xls"');
            header("Content-Disposition:attachment;filename=" . $filename . ".xls");
            $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
            $objWriter->save('php://output');
            exit;
        }
        return View::fetch();
    }

    public function meal_order()
    {
        $order_list = UserMealOrder::order('create_time', 'desc')->paginate(30);
        return View::assign([
            'order_list' => $order_list,
            'page'       => $order_list->render(),
        ])->fetch();
    }

    public function meal_info($order_id = '')
    {
        $order = UserMealOrder::where('order_id', '=', $order_id)->find();
        return View::assign([
            'order' => $order,
        ])->fetch();
    }

    public function meal_order_delete($order_id = '')
    {
        if (!Request::isAjax()) {
            return show_error('请求类型错误');
        }
        $order = UserMealOrder::where('order_id', '=', $order_id)->find();
        if (empty($order)) {
            return show_error('指定数据不存在');
        }
        $order->delete();
        return show_success('数据删除成功', 'admin/announce/meal_order');
    }

    public function recharge()
    {
        $recharge_list = UserRecharge::order('create_time', 'desc')->paginate(30);
        return View::assign([
            'recharge_list' => $recharge_list,
            'page'          => $recharge_list->render(),
        ])->fetch();
    }

    public function recharge_info($recharge_id = '')
    {
        $recharge = UserRecharge::where('recharge_id', '=', $recharge_id)->find();
        return View::assign([
            'recharge' => $recharge,
        ])->fetch();
    }

    public function recharge_delete($recharge_id = '')
    {
        if (!Request::isAjax()) {
            return show_error('请求类型错误');
        }
        $recharge = UserRecharge::where('recharge_id', '=', $recharge_id)->find();
        if (empty($recharge)) {
            return show_error('指定数据不存在');
        }
        $recharge->delete();
        return show_success('数据删除成功', 'admin/announce/recharge');
    }
}
